﻿#ifndef TBWORKER_H
#define TBWORKER_H

#include <QObject>
#include <QSharedPointer>
#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>
#include <locale>
#include <mutex>
#include <QNetworkAccessManager>
#include "busidate.h"


class tbWorker : public QObject
{
    Q_OBJECT
public:
    explicit tbWorker(QObject *parent = 0);
    ~tbWorker();

signals:
    void send_zjjk_reply(QByteArray reply);
    void send_log(const QString & handle);
    void send_error(const QString & error);




private:    
    QSharedPointer<BusiDate> m_busidate;
    QNetworkAccessManager * m_request_manager;
    QVariant cookies;

private:
    QString jcaptcha_code;
    QString name_ascii;
    QByteArray login_result;
    bool is_zjjk_success;

    //网络请求返回数据
    QByteArray jcaptcha_data;
    QByteArray zjjk_data;
    QByteArray ask_data;
    QByteArray a13_data;
    QByteArray note_data;

private:
    void get_jcaptcha_code();
    void get_zhname_code();
    void login();
    void m_login();
    void play_sound(const QString & path);

public:    
    void zjjk_check();
    void ask_check();
    void a13_check();
    void note_check();


public slots:
    void check();
    void get_zjjk_data();
    void get_ask_data();
    void get_a13_data();
    void get_note_data();

};


//获取验证码回调函数
inline size_t jcaptcha_callback(char * content,size_t size ,size_t count,QString * userptr)
{
#ifndef WIN32
    setlocale(LC_ALL, "C");
#endif
    size_t dataLength = size*count;
    tesseract::TessBaseAPI * api = new tesseract::TessBaseAPI();
    if(api->Init("./assets","eng"))
    {
        fprintf(stderr,"could not initialize apt");
        exit(-1);
    }

    Pix * image = pixReadMem(reinterpret_cast<const unsigned char*>(content),dataLength);
    api->SetImage(image);
    char * outText = api->GetUTF8Text();
    userptr->clear();
    userptr->append(outText);

    api->End();
    delete[] outText;
    pixDestroy(&image);
    delete api;
    return dataLength;
}

//数据请求回调函数
inline size_t request_callback(char * content,size_t size ,size_t count, QByteArray * user)
{
    std::mutex user_mutex;
    size_t dataLength = size*count;
    user_mutex.lock();
    user->append(content);
    user_mutex.unlock();
    return dataLength;
}



#endif // TBWORKER_H
